package com.ssm.subject.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.ssm.subject.common.entity.PageResult;
import com.ssm.subject.common.enums.IsDeletedFlagEnum;
import com.ssm.subject.common.util.IdWorkerUtil;
import com.ssm.subject.common.util.LoginUtil;
import com.ssm.subject.domain.bo.SubjectInfoBO;
import com.ssm.subject.domain.bo.SubjectLabelBO;
import com.ssm.subject.domain.bo.SubjectOptionBO;
import com.ssm.subject.domain.convert.SubjectInfoBOConvert;
import com.ssm.subject.domain.convert.SubjectLabelBOConverter;
import com.ssm.subject.domain.handler.subejct.SubejctTypeHandler;
import com.ssm.subject.domain.handler.subejct.SubjectTypeHandlerFactory;
import com.ssm.subject.domain.redis.RedisUtil;
import com.ssm.subject.domain.service.SubjectInfoDomainService;
import com.ssm.subject.domain.service.SubjectLikedDomainService;
import com.ssm.subject.infra.basic.entity.SubjectInfo;
import com.ssm.subject.infra.basic.entity.SubjectInfoEs;
import com.ssm.subject.infra.basic.entity.SubjectLabel;
import com.ssm.subject.infra.basic.entity.SubjectMapping;
import com.ssm.subject.infra.basic.service.SubjectEsService;
import com.ssm.subject.infra.basic.service.SubjectInfoService;
import com.ssm.subject.infra.basic.service.SubjectLabelService;
import com.ssm.subject.infra.basic.service.SubjectMappingService;
import com.ssm.subject.infra.entity.UserInfo;
import com.ssm.subject.infra.rpc.UserRpc;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.security.auth.Subject;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Log4j2
public class SubjectInfoDomainServiceImpl implements SubjectInfoDomainService {
    @Resource
    private SubjectInfoService subjectInfoServices;
    @Resource
    private SubjectTypeHandlerFactory subjectTypeHandlerFactory;
    @Resource
    private SubjectMappingService subjectMappingService;
    @Resource
    private SubjectLabelService subjectLabelService;
    @Resource
    private SubjectEsService subjectEsService;
    @Resource
    private UserRpc userRpc;
    @Resource
    private RedisUtil redisUtil;
    private static final String RANK_KEY = "subject_rank";
    @Resource
    private SubjectLikedDomainService subjectLikedDomainService;

    /**
     * 查询题目详情
     * @param subjectInfoBO
     * @return
     */
    @Override
    public SubjectInfoBO querySubjectInfo(SubjectInfoBO subjectInfoBO) {
        if(log.isInfoEnabled()) {
            log.info("SubjectInfoDomainService.querySubjectInfo.subjectInfoBO:{}", JSON.toJSONString(subjectInfoBO));
        }
        //先查询题目主表数据
        SubjectInfo subjectInfo = subjectInfoServices.queryById(subjectInfoBO.getId());
        //工厂 + 策略 查询具体类型题目的数据
        SubejctTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
        SubjectOptionBO subjectOptionBO = handler.query(subjectInfoBO.getId());
        //将主表数据info 和 具体题目数据(答案、选项信息) 一起转为 infoBo
        SubjectInfoBO bo = SubjectInfoBOConvert.INSTANCE.subjectOptionBoAndInfoToBo(subjectInfo, subjectOptionBO);
        //查询标签id->标签name
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setSubjectId(bo.getId());
        subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectMapping> subjectMappingList = subjectMappingService.queryByLabelId(subjectMapping);
        List<Long> labelIds = subjectMappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
        List<SubjectLabel> subjectLabelList = subjectLabelService.queryByLabelIds(labelIds);
        List<String> labelNames = subjectLabelList.stream().map(SubjectLabel::getLabelName).collect(Collectors.toList());
        bo.setLabelName(labelNames);

        //返回点赞数、是否点赞
        Integer likedCount = subjectLikedDomainService.getLikedCount(bo.getId().toString());
        Boolean liked = subjectLikedDomainService.isLiked(bo.getId().toString(), LoginUtil.getLoginId());
        bo.setLikedCount(likedCount);
        bo.setLiked(liked);
        return bo;
    }

    /**
     * 新增题目(工厂 + 策略解耦，否则单选调单选service，多选调多选，一大堆if)
     * 多表操作加事务，默认RuntimeException运行异常触发，这里设置为Exception只要方法执行过程遇到异常直接回滚
     * @param subjectInfoBO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SubjectInfoBO subjectInfoBO) {
        if(log.isInfoEnabled()) {
            log.info("SubjectInfoDomainService.add.subjectInfoBO:{}", JSON.toJSONString(subjectInfoBO));
        }
        //先插入主表info数据
        SubjectInfo subjectInfo = SubjectInfoBOConvert.INSTANCE.subjectInfoBoToInfo(subjectInfoBO);
        subjectInfoServices.insert(subjectInfo);
        //工厂 + 策略设计模式
        SubejctTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
        subjectInfoBO.setId(subjectInfo.getId()); //info表开启了主键映射，新增完会把id值赋值到实体类上
        handler.add(subjectInfoBO);
        //把题目、标签、分类的映射关系同步到mapping表中(每个题目对应的每个分类对应的每个标签都为一条数据,即1个题目在有3个标签且属于两个分类就有6条数据)
        List<Long> categoryIds = subjectInfoBO.getCategoryIds();
        List<Long> labelIds = subjectInfoBO.getLabelIds();
        //分类id和标签id在入口已经判空过了,在domain层肯定有值
        List<SubjectMapping> subjectMappingList = new ArrayList<>();
        categoryIds.forEach(categoryId -> {
            labelIds.forEach(labelId -> {
                SubjectMapping subjectMapping = new SubjectMapping();
                subjectMapping.setCategoryId(categoryId);
                subjectMapping.setLabelId(labelId);
                subjectMapping.setSubjectId(subjectInfo.getId());
                subjectMappingList.add(subjectMapping);
            });
        });
        subjectMappingService.batchInsert(subjectMappingList);

        //同步到es
        SubjectInfoEs subjectInfoEs = new SubjectInfoEs();
        subjectInfoEs.setDocId(new IdWorkerUtil(1, 1, 1).nextId()); //雪花算法生成id
        subjectInfoEs.setSubjectId(subjectInfoBO.getId()); //id在info和bo里都有值
        subjectInfoEs.setSubjectName(subjectInfoBO.getSubjectName());
        subjectInfoEs.setSubjectAnswer(subjectInfoBO.getSubjectAnswer());
        subjectInfoEs.setSubjectType(subjectInfoBO.getSubjectType().toString());
        subjectInfoEs.setCreateUser(LoginUtil.getLoginId());
        subjectInfoEs.setCreateTime(new Date().getTime());
        subjectEsService.insert(subjectInfoEs);

        //放入redis的Zset计入排行榜(当key不存在，会创建新的zset)
        redisUtil.addScore(RANK_KEY, LoginUtil.getLoginId(), 1);
    }

    /**
     * 查询题目列表、分页查询
     * @param subjectInfoBO
     * @return
     */
    @Override
    public PageResult<SubjectInfoBO> getSubjectPage(SubjectInfoBO subjectInfoBO) {
        if(log.isInfoEnabled()) {
            log.info("SubjectController.SubjectInfoDomainService.subjectInfoBO{}", JSON.toJSONString(subjectInfoBO));
        }
        PageResult<SubjectInfoBO> pageResult = new PageResult<>();
        pageResult.setPageSize(subjectInfoBO.getPageSize());
        pageResult.setPageNo(subjectInfoBO.getPageNo());
        SubjectInfo subjectInfo = SubjectInfoBOConvert.INSTANCE.subjectInfoBoToInfo(subjectInfoBO);
        int count = subjectInfoServices.countByCondition(subjectInfo, subjectInfoBO.getCategoryId(), subjectInfoBO.getLabelId());
        if(count == 0) {
            return pageResult;
        }
        //sql中第一条数据从0开始 limit(第几个数据开始，页容量)
        int start = (subjectInfoBO.getPageNo() - 1) * subjectInfoBO.getPageSize();
        List<SubjectInfo> subjectInfoList = subjectInfoServices.queryPage(subjectInfo, subjectInfoBO.getCategoryId()
                , subjectInfoBO.getLabelId(), start, subjectInfoBO.getPageSize());
        List<SubjectInfoBO> subjectInfoBOS = SubjectInfoBOConvert.INSTANCE.subjectInfosToBos(subjectInfoList);
        pageResult.setRecords(subjectInfoBOS);
        pageResult.setTotal(count);
        if(log.isInfoEnabled()) {
            log.info("SubjectController.SubjectInfoDomainService.PageResult{}", JSON.toJSONString(pageResult));
        }
        return pageResult;
    }

    /**
     * 关键词全文检索
     * @param subjectInfoBO
     * @return
     */
    @Override
    public PageResult<SubjectInfoEs> getSubjectPageBySearch(SubjectInfoBO subjectInfoBO) {
        SubjectInfoEs subjectInfoEs = new SubjectInfoEs();
        subjectInfoEs.setKeyword(subjectInfoBO.getKeyWord());
        subjectInfoEs.setPageNo(subjectInfoBO.getPageNo());
        subjectInfoEs.setPageSize(subjectInfoBO.getPageSize());
        PageResult<SubjectInfoEs> subjectInfoEsPageResult = subjectEsService.querySubjectList(subjectInfoEs);
        return subjectInfoEsPageResult;
    }

    /**
     * 获取题目贡献榜
     * 1.传统数据库实现排行榜 2.redis的zset实现排行榜
     * @return
     */
    @Override
    public List<SubjectInfoBO> getContributeList() {
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisUtil.rankWithScore(RANK_KEY, 0, 5);
        if(CollectionUtils.isEmpty(typedTuples)) {
            return Collections.emptyList();
        }
        List<SubjectInfoBO> subjectInfoBOList = new LinkedList<>();
        typedTuples.forEach(rank -> {
            SubjectInfoBO subjectInfoBO = new SubjectInfoBO();
            subjectInfoBO.setSubjectCount(rank.getScore().intValue());
            UserInfo userInfo = userRpc.getUserInfo(rank.getValue());
            subjectInfoBO.setCreateUserAvatar(userInfo.getAvatar());
            subjectInfoBO.setCreateUser(userInfo.getNickName());
            subjectInfoBOList.add(subjectInfoBO);
        });
        return subjectInfoBOList;

//        传统数据库实现排行榜
//        List<SubjectInfo> subjectInfoList = subjectInfoServices.getContributeList();
//        System.out.println(subjectInfoList);
//        if(CollectionUtils.isEmpty(subjectInfoList)) {
//            return Collections.emptyList();
//        }
//        List<SubjectInfoBO> subjectInfoBOList = new LinkedList<>();
//        subjectInfoList.forEach(subjectInfo -> {
//            SubjectInfoBO subjectInfoBO = new SubjectInfoBO();
//            subjectInfoBO.setSubjectCount(subjectInfo.getSubjectCount());
//            UserInfo userInfo = userRpc.getUserInfo(subjectInfo.getCreatedBy());
//            subjectInfoBO.setCreateUserAvatar(userInfo.getAvatar());
//            subjectInfoBO.setCreateUser(userInfo.getNickName());
//            subjectInfoBOList.add(subjectInfoBO);
//        });
//        return subjectInfoBOList;
    }
}
